import axios from 'axios';
import { Message, Loading } from 'element-ui';
import { reqTime, reqNo, getTokenId, getDesKeyFromCookie, getRSAKeyFromCookie } from '@/assets/js/utils';
import router from '@/router/index';
import JsEncrypt from 'jsencrypt/bin/jsencrypt';
import CryptoJS from 'crypto-js';

export const keyHex = CryptoJS.enc.Utf8.parse(getDesKeyFromCookie());

export const http = axios.create({
    // 非加密方式
    baseURL: process.env.API_URL,
    // baseURL: 'http://193.168.1.171:18002',
    // baseURL: 'https://asset.uter.com',
    timeout: 250000
});
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

let loadingInstance;
// 添加请求拦截器
http.interceptors.request.use(config => {
    loadingInstance = Loading.service({ fullscreen: true,text: '加载中' });
    return config;
}, error => {
    loadingInstance.close();
    console.log("request error:", error);
    return Promise.reject(error);
});

// 返回状态判断,添加响应拦截器
http.interceptors.response.use(
    (response) => {
        loadingInstance.close();
        if (response && response.data.length !== 0 && response.data !== undefined) {
            if(response.data.state.code === "200"){
                let ciphertext = CryptoJS.TripleDES.decrypt(response.data.ciphertext, keyHex, {
                    iv: CryptoJS.enc.Utf8.parse(keyHex),
                    mode: CryptoJS.mode.ECB,
                    padding: CryptoJS.pad.Pkcs7
                });
                ciphertext = CryptoJS.enc.Utf8.stringify(ciphertext);
                response.data.ciphertext = ciphertext;
                return response;
            }else{
                Message({
                    message: response.data?response.data.state.message:'网络错误',
                    type: 'error',
                    duration: 1800
                });
                if(!response.data || response.data.state.code === "402"){
                    router.push({path: '/login'});
                    return false;
                }
                // return Promise.reject(response);
                return response;
            }
        } else {
        }
    },
    (error) => {
        loadingInstance.close();
        Message({
            message: '网络异常',
            type: 'error',
            duration: 5000
        });
        return Promise.reject(error);
    }
);

// 加密报文
let params = (body) => {
    // 0. des加密请求参数
    let cipObj = {
        "tokenId": getTokenId(),
        body
    };
    console.log(cipObj);
    cipObj = JSON.stringify(cipObj);
    let desEncrypted = CryptoJS.TripleDES.encrypt(cipObj, keyHex, {
        iv: CryptoJS.enc.Utf8.parse(keyHex),
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let desEncryptedStr = desEncrypted.toString();

    // 1. 对密文进行MD5摘要
    let cipMd5 = CryptoJS.MD5(desEncryptedStr);
    let cipMd5Str = cipMd5.toString();

    // 2. 使用服务端的公钥对md5摘要进行加密,得到密文的签名（签名-sign）
    let jse = new JsEncrypt.JSEncrypt();
    jse.setPublicKey(getRSAKeyFromCookie());
    let RSAEncrypted = jse.encrypt(cipMd5Str);

    let user = JSON.parse(window.sessionStorage.getItem("sysUser"));
    let data = {
        "reqNo": reqNo(),
        "reqTime": reqTime(),
        "platformNo": user?user.platformNo:'1',
        "sign": RSAEncrypted,
        "channel": "0",
        "ciphertext": desEncryptedStr
    };
    return data;
};

// 未加密报文
let paramsData = (body) => {
    let user = JSON.parse(window.sessionStorage.getItem("sysUser"));
    let data = {
        "reqNo": reqNo(),
        "reqTime": reqTime(),
        "platformNo": user?user.platformNo:'1',
        "operatorNo": user.userNo,
        "channel": "0",
        "tokenId": getTokenId(),
        body
    };
    console.log('data', data);
    return data;
};

// 开户
let apiAddUser = "/api-user/userInfo";
// 会员
let apiuser = "/api-user/user";
// 系统
let apiys = "/api-sys/sys";
// 产品
let apiproduct = "/api-product/product";
// 借款
let apiLoan = "/api-loan/loan";
// 还款
let apiepay = "/api-repay/repay";
// 渠道
let apihannel = "/api-channel/channel";
// 数据
let apiData = "/api-data/data";
// 下载
let apiDownload = "/loan/download";

/**
 * 页面接口
 * */
// 退回
export const returnLoanCheck = (body) => { return http.post(`${apiLoan}/returnLoanCheck`, params(body)).then(); };
// 借款申请列表
export const listLoanInfo = (body) => { return http.post(`${apiData}/listLoanInfo`, params(body)).then(); };
// 借款详情
export const getLoanInfo = (body) => { return http.post(`${apiData}/getLoanInfo`, params(body)).then(); };
// 借款详情two
export const getLoanCheckInfo = (body) => { return http.post(`${apiData}/getLoanCheckInfo`, params(body)).then(); };
// 借款详情表字段
export const listProductInfo = (body) => { return http.post(`${apiproduct}/listProductInfo`, params(body)); };
// 借款申请
export const saveLoanInfo = (body) => { return http.post(`${apiLoan}/saveLoanInfo`, params(body)).then(); };
// 编辑借款申请
export const editLoanInfo = (body) => { return http.post(`${apiLoan}/editLoanInfo`, params(body)).then(); };
// 获取资料上传字段
export const editLoanData = (body) => { return http.post(`${apiLoan}/editLoanData`, params(body)).then(); };
// 获取借款资料
export const listLoanData = (body) => { return http.post(`${apiLoan}/listLoanData`, params(body)).then(); };
// 借款申请资料上传
export const saveLoanData = (body) => { return http.post(`${apiLoan}/saveLoanData`, params(body)).then(); };
// 删除借款资料
export const deleteLoanData = (body) => { return http.post(`${apiLoan}/delete/loanData`, params(body)).then(); };
// 获取图片验证码
export const imageCode = (body) => { return http.post(`${apihannel}/imageCode`, params(body)).then(); };
// 发送短信验证码
export const sendSms = (body) => { return http.post(`${apihannel}/sendSms`, params(body)).then(); };
// 验证短信验证码
export const verifyCode = (body) => { return http.post(`${apihannel}/verifyCode`, params(body)).then(); };
// 借款人开户详情
export const loanUserInfo = (body) => { return http.post(`${apiLoan}/loanUserInfo`, params(body)).then(); };
// 借款用户注册及开通银行托管
export const buserSave = (body) => { return http.post(`${apihannel}/user/buserSave`, params(body)).then(); };
// 开通海口银行托管
export const borrowAccountOpen = (body) => { return http.post(`${apihannel}/user/borrowAccountOpen`, params(body)).then(); };
// 删除借款申请列表某条记录
export const deleteLoanInfo = (body) => { return http.post(`${apiLoan}/deleteLoanInfo`, params(body)).then(); };
// 开户
export const addUser = (body) => { return http.post(`${apiAddUser}/add`, params(body)).then(); };
// 开户确定
export const updateLoanCheck = (body) => { return http.post(`${apiLoan}/updateLoanCheck`, params(body)).then(); };
// 面签列表
export const listLoanSign = (body) => { return http.post(`${apiData}/listLoanSign`, params(body)).then(); };
// 借款人面签详情、会员详情
export const userLoanInfo = (body) => { return http.post(`${apiData}/userLoanInfo`, params(body)).then(); };
// 面签确认
export const signConfirm = (body) => { return http.post(`${apiLoan}/signConfirm`, params(body)).then(); };
// 面签批复
export const signCheck = (body) => { return http.post(`${apiLoan}/signCheck`, params(body)).then(); };
// 家访列表
export const listLoanVisit = (body) => { return http.post(`${apiData}/listLoanVisit`, params(body)).then(); };
// 家访
export const visitCheck = (body) => { return http.post(`${apiLoan}/upload/visitCheck`, params(body)).then(); };
// 家访
export const visitConfirm = (body) => { return http.post(`${apiLoan}/visitConfirm`, params(body)).then(); };
// 协议上传列表
export const listLoanProtocol = (body) => { return http.post(`${apiData}/listLoanProtocol`, params(body)).then(); };
// 查询借款合同信息
export const listProtocolInfo = (body) => { return http.post(`${apiLoan}/upload/listProtocolInfo`, paramsData(body)).then(); };
// 协议上传
export const protocolCheck = (body) => { return http.post(`${apiLoan}/upload/protocolCheck`, params(body)).then(); };
// 资产审核列表
export const listLoanAssetConfirm = (body) => { return http.post(`${apiData}/listLoanAssetConfirm`, params(body)).then(); };
// 资产确认
export const assetCheck = (body) => { return http.post(`${apiLoan}/assetCheck`, params(body)).then(); };
// 资产管理列表
export const listLoanAsset = (body) => { return http.post(`${apiData}/listLoanAsset`, params(body)).then(); };
// 会员列表
export const listUserInfo = (body) => { return http.post(`${apiData}/listUserInfo`, params(body)).then(); };
// // 会员详情
// export const userLoanInfo = (body) => { return http.post(`${apiLoan}/userLoanInfo`, params(body)).then(); };
// 借款详情列表
export const listRepayProject = (body) => { return http.post(`${apiData}/listRepayProject`, params(body)).then(); };
// 还款明细列表
export const listRepayInfo = (body) => { return http.post(`${apiData}/listRepayInfo`, params(body)).then(); };
// 财务审核列表
export const listLoanAudit = (body) => { return http.post(`${apiData}/listLoanAudit`, params(body)); };
// 费用核算表
export const loadCostAuditingData = (body) => { return http.post(`${apiLoan}/listLoanFee`, params(body)); };
// 费用核算明细表
export const listLoanFee = (body) => { return http.post(`${apiLoan}/listLoanFee`, params(body)); };
// 费用核算表提交
export const auditCheck = (body) => { return http.post(`${apiLoan}/auditCheck`, params(body)); };
// 费用核算表修改
export const auditModify = (body) => { return http.post(`${apiLoan}/auditModify`, params(body)); };
// 风控初审
export const listLoanRisk = (body) => { return http.post(`${apiData}/listLoanRisk`, params(body)).then(); };
// 风控初审的借款详情
export const riskLoanInfo = (body) => { return http.post(`${apiData}/riskLoanInfo`, params(body)).then(); };
// 风控初审批复
export const riskCheck = (body) => { return http.post(`${apiLoan}/riskCheck`, params(body)).then(); };
// 风控初审确认
export const riskConfirm = (body) => { return http.post(`${apiLoan}/riskConfirm`, params(body)).then(); };
// 风控复审
export const listLoanRM = (body) => { return http.post(`${apiData}/listLoanRM`, params(body)).then(); };
// 风控复审确认
export const rmCheck = (body) => { return http.post(`${apiLoan}/rmCheck`, params(body)).then(); };
// 发标列表
export const listLoanProject = (body) => { return http.post(`${apiData}/listLoanProject`, params(body)).then(); };
// 发标前查询的接口   发标查询借款信息的接口getLoanProject，改成userLoanInfo
export const getLoanProjectInfo = (body) => { return http.post(`${apiData}/getLoanProjectInfo`, params(body)).then(); };
// 发标
export const createLoanProject = (body) => { return http.post(`${apiLoan}/createLoanProject`, params(body)).then(); };
// 发标审核
export const createCheck = (body) => { return http.post(`${apiLoan}/createCheck`, params(body)).then(); };
// 放款
export const out = (body) => { return http.post(`${apiLoan}/out`, params(body)).then(); };
// 创建还款
export const createRepay = (body) => { return http.post(`${apiLoan}/createRepay`, params(body)).then(); };
